﻿package Chapter06;
// 將 StepIntoJava.java 內容替換為下列代碼即可運行
//======================================================================
//public class StepIntoJava {
//	public static void main(String[] args) {
//		Ch06DotComGame app = new Ch06DotComGame();
//		app.run();
//	}	
//}
//======================================================================

import java.util.ArrayList;

public class DotComBust {
	int numOfCompanies = 4;
	int sizeOfCompany = 3;

	GameHelper helper = new GameHelper();
	ArrayList<DotCom> dotComs = new ArrayList<DotCom>();
	
	void run() {
		setupGame();
		
		int guessCount = startPlaying();
		
		if (guessCount <= 18) {
			System.out.println("恭喜你贏得勝利, 一共猜了 "+guessCount+" 次");
		} else {
			System.out.println("花太多次猜囉~, 一共猜了 "+guessCount+" 次");
		}
	}

	public void setupGame() {
		for (int i = 0; i < numOfCompanies; ++i) {
			// 宣告並初始化一個 DotCom 物件
			DotCom theCompany = new DotCom();
			theCompany.setName("公司"+(i+1));	// 設定公司名字
			theCompany.setIndex(i+1);
			ArrayList<String> places = helper.placeDotCom(sizeOfCompany);	// 取得空位
			//將空位設定到公司資料裡 // setLocation
			theCompany.setLocationCells(places);
			//並放到 dotComs 中
			dotComs.add(theCompany);
		}
	}

	public int startPlaying() {
		//取得使用者輸入
		String guess;
		int guessCount = 0;
		while(!dotComs.isEmpty()) {
			guess = helper.getUserInput("請輸入要攻擊的位置: ");
			if (guess.equals("p")) {
				printAllMap();
				continue;
			}
			guessCount++;
			boolean isMissed = true;
			
			for (DotCom company : dotComs) { //對三家公司進行處理
				String result = company.checkYourself(guess);
				if (result.equals("hit")) {
					System.out.println("你擊中了「"+company.getName()+"」");
					isMissed = false;
					break;
				} else if (result.equals("kill")) {
					System.out.println(company.getName()+"被摧毀了~");
					dotComs.remove(company);
					isMissed = false;
					break;
				}
			}
			if (isMissed) {
				System.out.println("喔喔喔~沒有打中");
			}
		}
		return guessCount;
	}
	
	public void printAllMap() {
		Character rowIndex = 65;
		//System.out.println("  1  2  3  4  5  6  7");
		System.out.println("  0  1  2  3  4  5  6");
		for (int i = 0; i < 7; i++) {
			System.out.print((rowIndex++).toString());
			for (int j = 0; j < 7; j++) {
				System.out.printf("[%s]",getCompanyAt(i,j));
			}
			System.out.println("");
		}
	}
	
	public String getCompanyAt(int x, int y) {
		Character rowIndex = (char)(65+x);
		Integer colIndex = y;
		String loc = rowIndex.toString()+colIndex.toString();
		loc = loc.toLowerCase();
		for (DotCom company : dotComs) {
			if (company.hasPlace(loc)) {
				return ""+company.getIndex();
			}
		}
		return " ";
	}
}
